package com.github.benmanes.caffeine.demo;

import com.github.benmanes.caffeine.cache.*;
import com.github.benmanes.caffeine.cache.stats.CacheStats;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.PolyNull;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class MultiWriteDemo {
    static System.Logger logger = System.getLogger(MultiWriteDemo.class.getName());

    public static void hello(String[] args) {
        System.out.println("args = " + args);
    }

    enum DemoSystemScheduler implements Scheduler {
        INSTANCE;

        @Override
        public Future<?> schedule(Executor executor, Runnable command, long delay, TimeUnit unit) {
            Executor delayedExecutor = CompletableFuture.delayedExecutor(delay, unit, executor); //ScheduledThreadPoolExecutor
            return CompletableFuture.runAsync(command, delayedExecutor);
        }
    }

    public static void main(String... args) throws Exception {
        Cache<String, String> cache = Caffeine.newBuilder()
//                .scheduler( Scheduler.systemScheduler())
                .scheduler(DemoSystemScheduler.INSTANCE)
                //最大个数限制
                //最大容量1024个，超过会自动清理空间
//                .maximumSize(1024)
                //访问后过期（包括读和写）
                //5秒没有读写自动删除
                .expireAfterAccess(10, TimeUnit.SECONDS)
                //写后过期
                .expireAfterWrite(10, TimeUnit.HOURS)
                //写后自动异步刷新
                .refreshAfterWrite(10, TimeUnit.HOURS)
                .maximumSize(32)
                //初始化容量
                .initialCapacity(1)


                .recordStats()
                .removalListener(((key, value, cause) -> {
                    //清理通知 key,value ==> 键值对   cause ==> 清理原因
                    System.out.println("removed key=" + key);
                }))

                //使用CacheLoader创建一个LoadingCache
                .build(new CacheLoader<String, String>() {
                    //同步加载数据
                    @Nullable
                    @Override
                    public String load(@NonNull String key) throws Exception {
                        System.out.println("loading  key=" + key);
                        return "value_" + key;
                    }

                    //异步加载数据
                    @Nullable
                    @Override
                    public String reload(@NonNull String key, @NonNull String oldValue) throws Exception {
                        System.out.println("reloading  key=" + key);
                        return "value_" + key;
                    }
                });

        String val = cache.get("name:", k -> {
            System.out.println("key:" + k);
            return "一个高并发 研究社群";
        });

        int i = 0;
        //添加值
        while (true) {
            i++;
            TimeUnit.SECONDS.sleep(1);
            for (int j = 0; j < 100; j++) {
                cache.put("name:" + i + "_" + j, "疯狂创客圈");
                cache.put("key:" + i + "_" + j, "一个高并发 研究社群");

            }
            //获取值
            System.out.println("key:" + i + " / " + cache.getIfPresent("key:" + i));
            for (int ii = 1; ii < 3; ii++) {
                for (int j = 0; j < 100; j++) {
                    cache.getIfPresent("name:" + ii + "_" + j);
                    cache.getIfPresent("key:" + ii + "_" + j);

                }
            }

            CacheStats status = cache.stats();

        }


    }

}
